﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace RouteTiming.Data
{
    public partial class RouteTimingContext
    {
        /// <summary>
        /// Fired when an event is added to the context
        /// </summary>
        public event Action<Event> OnEventAdded;

        partial void OnContextCreated()
        {
            this.ObjectStateManager.ObjectStateManagerChanged += new System.ComponentModel.CollectionChangeEventHandler(ObjectStateManager_ObjectStateManagerChanged);
        }

        private void ObjectStateManager_ObjectStateManagerChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
        {
            var newEvent = e.Element as Event;
            if
            (
                (e.Action == CollectionChangeAction.Add)
                &&
                (newEvent != null)
            )
                this.FireEventAdded(newEvent);
        }

        private void FireEventAdded(Event newEvent)
        {
            // Filling auto-generated values

            if (newEvent.Id == Guid.Empty)
                newEvent.Id = Guid.NewGuid();

            newEvent.TimeAdded = DateTime.Now;

            if (this.OnEventAdded != null)
                this.OnEventAdded(newEvent);
        }

    }
}
